#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include"../include/main.h"
#include"../include/bst.h"
#include"../include/create_vfs.h"
#include"../include/vfs_errorcodes.h"
#include"../include/constants.h"

void create_vfs(char vfs_label[],int vfs_size)
{
	int n,i=0,flag=0;
	char *t;
	size_t s,size;
	FILE *vfs;
	mainheader *header,*reader; 
	char blk_array[BLOCK_SIZE],invalid_char[]={'/'};
	
	vfs = fopen(vfs_label,"rb");
	if(strlen(vfs_label) > VFS_LABEL_SIZE)
		printf("%s_FAILURE %s\n",glb_command,ERR_VFS_CREATE_05);
	else if(vfs_size <= 0 || vfs_size > 1024)
		printf("%s_FAILURE %s\n",glb_command,ERR_VFS_CREATE_04);
	else if((t=strchr(vfs_label,invalid_char[i])) != NULL)
		printf("%s_FAILURE %s\n",glb_command,ERR_VFS_CREATE_03);	
	else if(vfs != NULL)
		printf("%s_FAILURE %s\n",glb_command,ERR_VFS_CREATE_01);
	else 
	{
		//close(vfs);
		vfs = fopen(vfs_label,"wb");
		if(vfs==NULL)
		{
			printf("%s_FAILURE %s\n",glb_command,ERR_VFS_CREATE_02);
		}
		else
		{	
			size_of_vfs=vfs_size;
			header=(mainheader *)malloc(sizeof(mainheader));
			strcpy(header->filelabel,vfs_label);
			header->max_fd=vfs_size;
			header->used_fd=0;
			for(i=0;i<vfs_size;i++)
			{
				header->fd_array[i]=(fdesc *)malloc(sizeof(fdesc));
				header->f_list[i]=0;
				strcpy(header->fd_array[i]->filename," ");
				strcpy(header->fd_array[i]->filepath," ");
				header->fd_array[i]->filetype=0;
				header->fd_array[i]->file_size=0;
				header->fd_array[i]->blk_num=0;
			}
			size=fwrite(&flag,INT_SIZE,1,vfs);
			size=fwrite(header->filelabel,MAX_NAME,1,vfs);//mainheader->file_label
			size=fwrite(&header->max_fd,INT_SIZE,1,vfs);//max fd v can create
			size=fwrite(&header->used_fd,INT_SIZE,1,vfs);//no of used files
			size=fwrite(header->fd_array,sizeof(header->fd_array),1,vfs);
			size=fwrite(header->f_list,sizeof(header->f_list),1,vfs);
			for(n=0;n<vfs_size;n++)
				s=fwrite(blk_array,sizeof(blk_array),1,vfs);
			printf("createvfs_SUCCESS\n");
		}
	}
	if(vfs != NULL)
	close(vfs);
}
